/*
Copyright The Helm Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

Original file: https://github.com/helm/helm/blob/v3.2.0/pkg/releaseutil/kind_sorter.go
*/

package addonutil

import (
	"fmt"
	"sort"

	"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
)

var ListKinds = []string{
	"ConfigMapList",
	"SecretList",
	"ClusterRoleList",
	"ClusterRoleBindingList",
	"RoleList",
	"RoleBindingList",
}

// KindSortOrder is an ordering of Kinds.
type KindSortOrder []string

// InstallOrder is the order in which manifests should be installed (by Kind).
//
// Those occurring earlier in the list get installed before those occurring later in the list.
var InstallOrder KindSortOrder = []string{
	"Namespace",
	"NetworkPolicy",
	"ResourceQuota",
	"LimitRange",
	"PodSecurityPolicy",
	"PodDisruptionBudget",
	"ServiceAccount",
	"Secret",
	"SecretList",
	"ConfigMap",
	"ConfigMapList",
	"StorageClass",
	"PersistentVolume",
	"PersistentVolumeClaim",
	"CustomResourceDefinition",
	"ClusterRole",
	"ClusterRoleList",
	"ClusterRoleBinding",
	"ClusterRoleBindingList",
	"Role",
	"RoleList",
	"RoleBinding",
	"RoleBindingList",
	"Service",
	"MutatingWebhookConfiguration",
	"ValidatingWebhookConfiguration",
	"Certificate",
	"Issuer",
	"Job",
	"DaemonSet",
	"Pod",
	"ReplicationController",
	"ReplicaSet",
	"Deployment",
	"HorizontalPodAutoscaler",
	"StatefulSet",
	"CronJob",
	"IngressClass",
	"Ingress",
	"APIService",
}

// UninstallOrder is the order in which manifests should be uninstalled (by Kind).
//
// Those occurring earlier in the list get uninstalled before those occurring later in the list.
var UninstallOrder KindSortOrder = []string{
	"APIService",
	"Ingress",
	"IngressClass",
	"Service",
	"CronJob",
	"Job",
	"StatefulSet",
	"HorizontalPodAutoscaler",
	"Deployment",
	"ReplicaSet",
	"ReplicationController",
	"Pod",
	"DaemonSet",
	"RoleBindingList",
	"RoleBinding",
	"RoleList",
	"Role",
	"ClusterRoleBindingList",
	"ClusterRoleBinding",
	"ClusterRoleList",
	"ClusterRole",
	"CustomResourceDefinition",
	"PersistentVolumeClaim",
	"PersistentVolume",
	"StorageClass",
	"ConfigMapList",
	"ConfigMap",
	"SecretList",
	"Secret",
	"ServiceAccount",
	"PodDisruptionBudget",
	"PodSecurityPolicy",
	"LimitRange",
	"ResourceQuota",
	"NetworkPolicy",
	"Namespace",
}

func SortInstallUnstructuredByKind(unstructs []unstructured.Unstructured) []unstructured.Unstructured {
	sort.SliceStable(unstructs, func(i, j int) bool {
		return lessByKindInstall(unstructs[i].GetKind(), unstructs[j].GetKind(), InstallOrder)
	})
	return unstructs
}

func SortUninstallUnstructuredByKind(unstructs []unstructured.Unstructured) []unstructured.Unstructured {
	sort.SliceStable(unstructs, func(i, j int) bool {
		return lessByKindUninstall(unstructs[j].GetKind(), unstructs[i].GetKind(), UninstallOrder)
	})
	return unstructs
}

func lessByKindUninstall(kindA string, kindB string, o KindSortOrder) bool {
	ordering := make(map[string]int, len(o))
	for v, k := range o {
		ordering[k] = v
	}

	first, aok := ordering[kindA]
	second, bok := ordering[kindB]

	if !aok && !bok {
		// if both are unknown then sort alphabetically by kind, keep original order if same kind
		if kindA != kindB {
			return kindA < kindB
		}
		return first < second
	}
	// unknown kind is first
	if !aok {
		return true
	}
	if !bok {
		return false
	}
	// sort different kinds, keep original order if same priority
	return first < second
}

func lessByKindInstall(kindA string, kindB string, o KindSortOrder) bool {
	ordering := make(map[string]int, len(o))
	for v, k := range o {
		ordering[k] = v
	}

	first, aok := ordering[kindA]
	second, bok := ordering[kindB]

	if !aok && !bok {
		// if both are unknown then sort alphabetically by kind, keep original order if same kind
		if kindA != kindB {
			return kindA < kindB
		}
		return first < second
	}
	// unknown kind is last
	if !aok {
		return false
	}
	if !bok {
		return true
	}
	// sort different kinds, keep original order if same priority
	return first < second
}

func IsListKind(kind string) bool {
	for _, listKind := range ListKinds {
		if listKind == kind {
			return true
		}
	}
	return false
}

// UnwrapList 解开List类型的资源，返回解开后的资源列表
func UnwrapList(unstruct unstructured.Unstructured) ([]unstructured.Unstructured, error) {
	if !IsListKind(unstruct.GetKind()) {
		return []unstructured.Unstructured{unstruct}, nil
	}

	items, found, err := unstructured.NestedSlice(unstruct.Object, "items")
	if err != nil {
		return nil, err
	}
	if !found {
		return nil, fmt.Errorf("no items found in list")
	}

	var unwrapped []unstructured.Unstructured
	for _, item := range items {
		unwrapped = append(unwrapped, unstructured.Unstructured{Object: item.(map[string]interface{})})
	}
	return unwrapped, nil
}
